/******************************************************************************************************
Copyright (C) 2015 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/

/*globals mainWindow, settings, Application, Dir, File, TextStream, MessageBox, ProcessingParametersReporter_Configuration*/

/*jslint plusplus: true, indent: 4, continue:true */

function ProcessingParametersReporter_Viewer(aLaunched) {
	"use strict";

	if (aLaunched !== undefined && aLaunched) {
		return;
	}

	//Main vars
	var dialog, processingParametersReporter_Viewer, processingParametersReporter_Configuration, current1DTemplate, current2DTemplate,
		dataTemplates, current1DTemplateKey, current2DTemplateKey, currentDataTemplatesKey, showDialog;

	//Registry Entries
	current1DTemplateKey = "Processing Parameters Report/Current 1D Template";
	current2DTemplateKey = "Processing Parameters Report/Current 2D Template";
	currentDataTemplatesKey = "Processing Parameters Report/Data Templates";

	//Load registy information
	current1DTemplate = settings.value(current1DTemplateKey, -1);
	current2DTemplate = settings.value(current2DTemplateKey, -1);

	//-------------------INSTANCE CLASS METHODS-------------------------------
	ProcessingParametersReporter_Viewer.prototype.loadComboboxes = function (aData) {
		var counter1D, counter2D, i;

		//Load Comboboxes by using the the information above
		if (aData.length === 0) {
			MessageBox.critical("The default templates deployed with the Mnova Software don't exist any longer");
		} else {
			counter1D = 0;
			counter2D = 0;
			for (i = 0; i < aData.length; i++) {
				if (Number(aData[i].dim) === 1) {
					dialog.widgets.cb1D.addItem(aData[i].name);
					if (current1DTemplate === -1 && aData[i].name.trim() === "1D HTML Text") {
						current1DTemplate = counter1D;
					}
					counter1D++;
				} else if (Number(aData[i].dim) === 2) {
					dialog.widgets.cb2D.addItem(aData[i].name);
					if (current2DTemplate === -1 && aData[i].name.trim() === "2D HTML Text") {
						current2DTemplate = counter2D;
					}
					counter2D++;
				}
			}
		}
	};

	//-------------------STATIC CLASS METHODS-------------------------------
	ProcessingParametersReporter_Viewer.updatePath1DLabel = function (aLength) {
		var i, text, auxDataTemplates;

		auxDataTemplates = [];
		for (i = 0; i < dataTemplates.length; i++) {
			if (dataTemplates[i].dim === 1) {
				auxDataTemplates.push(dataTemplates[i].path);
			}
		}
		if (auxDataTemplates.length > 0) {
			text = auxDataTemplates[dialog.widgets.cb1D.currentIndex];
			dialog.widgets.lb1DPathValue.toolTip = text;
			dialog.widgets.lb1DPathValue.text = "<font color = 'blue'>";
			if (text.length > aLength) {
				dialog.widgets.lb1DPathValue.text += text.substring(0, (aLength / 2)) + "..." + text.substring((text.length - (aLength / 2)), text.length);
			} else {
				dialog.widgets.lb1DPathValue.text += text;
			}
			dialog.widgets.lb1DPathValue.text += "</font>";
		}
	};

	ProcessingParametersReporter_Viewer.updatePath2DLabel = function (aLength) {
		var i, text, auxDataTemplates;

		auxDataTemplates = [];
		for (i = 0; i < dataTemplates.length; i++) {
			if (dataTemplates[i].dim === 2) {
				auxDataTemplates.push(dataTemplates[i].path);
			}
		}
		if (auxDataTemplates.length > 0) {
			text = auxDataTemplates[dialog.widgets.cb2D.currentIndex];
			dialog.widgets.lb2DPathValue.toolTip = text;
			dialog.widgets.lb2DPathValue.text = "<font color = 'blue'>";
			if (text.length > aLength) {
				dialog.widgets.lb2DPathValue.text += text.substring(0, (aLength / 2)) + "..." + text.substring((text.length - (aLength / 2)), text.length);
			} else {
				dialog.widgets.lb2DPathValue.text += text;
			}
			dialog.widgets.lb2DPathValue.text += "</font>";
		}
	};

	//---------------------Load UI--------------------------------
	dialog = Application.loadUiFile('ricares:ProcessingParametersReporter_Viewer.ui');
	dialog.show();

	//Retrieve data by searching the template files into the ricares directories
	dataTemplates = [];
	processingParametersReporter_Viewer = new ProcessingParametersReporter_Viewer(true);
	processingParametersReporter_Configuration = new ProcessingParametersReporter_Configuration();
	dataTemplates = processingParametersReporter_Configuration.getDataTemplates();
	processingParametersReporter_Viewer.loadComboboxes(dataTemplates);

	//Update selection
	dialog.widgets.cb1D.currentIndex = current1DTemplate;
	ProcessingParametersReporter_Viewer.updatePath1DLabel(70);
	dialog.widgets.cb2D.currentIndex = current2DTemplate;
	ProcessingParametersReporter_Viewer.updatePath2DLabel(70);

	//---------------------Signals and Slots Management-----------------
	//Detect a change related to the 1D Combobox
	dialog.widgets.cb1D['currentIndexChanged(int)'].connect(this, function () { ProcessingParametersReporter_Viewer.updatePath1DLabel(70); });
	//Detect a change related to the 2D Combobox
	dialog.widgets.cb2D['currentIndexChanged(int)'].connect(this, function () { ProcessingParametersReporter_Viewer.updatePath2DLabel(70); });

	//-------------------MAIN PROGRAM-------------------------------
	showDialog = true;
	while (showDialog) {
		//Check if cancle button is pulsed by user
		if (!dialog.exec()) {
			return;
		}
		showDialog = false;
	}

	//Save entries to registry
	settings.setValue(current1DTemplateKey, dialog.widgets.cb1D.currentIndex);
	settings.setValue(current2DTemplateKey, dialog.widgets.cb2D.currentIndex);
	settings.setValue(currentDataTemplatesKey, JSON.stringify(dataTemplates));
}

function ProcessingParametersReporter_Configuration() {
	"use strict";

	//Instance Attributes
	this.dataTemplates = [];

	//-------------------INSTANCE CLASS METHODS-------------------------------
	ProcessingParametersReporter_Configuration.prototype.readFile = function (aPathFile) {
		var stream, file;

		file = new File(aPathFile);
		file.open(File.ReadOnly);
		stream = new TextStream(file);
		stream.codec =  "UTF-8";
		stream = stream.readAll();
		file.close();
		return stream;
	};

	ProcessingParametersReporter_Configuration.prototype.getDataTemplates = function (aDim) {
		var txtPaths, auxTxtPaths, i, stream, regex, tag, m, dimension, aux, aux2, ricadirs;

		txtPaths = [];
		auxTxtPaths = [];
		tag = "##\!\!";
		ricadirs = Dir.searchPaths("ricares").reverse();
		while (ricadirs.length) {
			auxTxtPaths = new Dir(ricadirs.pop()).entryListAdv("*.txt", Dir.Files, Dir.Name);
			while (auxTxtPaths.length) {
				txtPaths.push(auxTxtPaths.pop());
			}
		}
		for (i = 0; i < txtPaths.length; i++) {
			stream = this.readFile(txtPaths[i]);
			regex = new RegExp("^(\\t| )*" + tag + ".*", "m");
			do {
				m = regex.exec(stream);
				if (m) {
					aux = m.toString().indexOf("Dim:") + "Dim:".length;
					aux2 = m.toString().indexOf("Name:") + "Name:".length;
					dimension =  Number(m.toString().substring(aux, (aux + 2)));
					if ((aux > -1) && (aux2 > 1)) {
						if (aDim === undefined || (aDim !== undefined && (dimension === aDim))) {
							this.dataTemplates.push({});
							this.dataTemplates[this.dataTemplates.length - 1].dim = dimension;
							this.dataTemplates[this.dataTemplates.length - 1].name = m.toString().substring(aux2, m.toString().length - 1);
							this.dataTemplates[this.dataTemplates.length - 1].path = txtPaths[i];
						}
					}
					break;
				}
			} while (m);
		}

		return this.dataTemplates;
	};

	ProcessingParametersReporter_Configuration.prototype.getDefaultTemplateIndex = function (aDim) {
		var i, counter1D, counter2D;

		counter1D = 0;
		counter2D = 0;
		for (i = 0; i < this.dataTemplates.length; i++) {
			if (Number(this.dataTemplates[i].dim) === 1) {
				if (aDim === 1 && this.dataTemplates[i].name.trim() === "1D HTML Text") {
					return counter1D;
				}
				counter1D++;
			} else if (Number(this.dataTemplates[i].dim) === 2) {
				if (aDim === 2 && this.dataTemplates[i].name.trim() === "2D HTML Text") {
					return counter2D;
				}
				counter2D++;
			}
		}
	};

	ProcessingParametersReporter_Configuration.prototype.filterTemplateByDimension = function (aDim) {
		var i;

		for (i = 0; i < this.dataTemplates.length; i++) {
			if (Number(this.dataTemplates[i].dim) !== aDim) {
				this.dataTemplates.splice(i, 1);
				i--;
			}
		}

		return this.dataTemplates;
	};

	ProcessingParametersReporter_Configuration.prototype.setDataTemplates = function (aDataTemplates) {

		if (aDataTemplates !== undefined) {
			this.dataTemplates = aDataTemplates;
		}
	};
}
